/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ws;

import bean.CurrencyLocal;
import entity.Currency;
import java.math.BigDecimal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

/**
 *
 * @author Vojtisek
 */
@WebService()
public class ExchangerService {

    private static final Logger logger = Logger.getLogger("ExchangerService");
    @EJB
    private CurrencyLocal ejbRef;

    @WebMethod(operationName = "exchange")
    public BigDecimal exchange(@WebParam(name = "amount") BigDecimal amount, @WebParam(name = "currencyFrom") String currencyFromString, @WebParam(name = "currencyTo") String currencyToString) throws Exception {
        try {
            currencyFromString = currencyFromString.toUpperCase();
            currencyToString = currencyToString.toUpperCase();
            Currency currencyFrom = ejbRef.find(currencyFromString);
            Currency currencyTo = ejbRef.find(currencyToString);
            BigDecimal result = null;
            result = amount.multiply(currencyFrom.getRate());
            result = result.divide(currencyTo.getRate(), 2, BigDecimal.ROUND_DOWN);
            return result;
        } catch (Exception ex) {
            throw ex;
        }
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "create")
    public String create() {
        try {
            ejbRef.create("CZK", BigDecimal.valueOf(1));
            ejbRef.create("USD", BigDecimal.valueOf(20));
            ejbRef.create("EUR", BigDecimal.valueOf(30));
            return "ok";
        } catch (Exception ex) {
            logger.log(Level.SEVERE, null, ex);
            return "error " + ex.getMessage();
        }

    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "exchangeTest")
    public String exchangeTest(@WebParam(name = "amount") int amountInt, @WebParam(name = "currencyFrom") String currencyFromString, @WebParam(name = "currencyTo") String currencyToString) throws Exception {
        return exchange(new BigDecimal(amountInt), currencyFromString, currencyToString).toString();
    }
    // Add business logic below. (Right-click in editor and choose
    // "Web Service > Add Operation"
}
